package com.it.user.controller;

import com.it.common.config.ResponseResult;
import com.it.common.config.ResultBean;
import com.it.common.utils.JwtUtils;
import com.it.user.entity.UserEntity;
import com.it.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用户登录 目前只能通过用户名进行登录
     */
    @PostMapping("/login")
    public ResponseEntity<ResponseResult<Map<String, Object>>> login(@RequestBody UserEntity user) {
        if (user == null || user.getName() == null || user.getPassword() == null) {
            return ResponseEntity.badRequest().body(ResponseResult.error(ResultBean.NOT_NULL.value(), ResultBean.NOT_NULL.description()));
        }

        try {
            UserEntity loggedInUser = userService.findUserByUsername(user.getName());

            if (loggedInUser == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseResult.error(ResultBean.LOGIN_FAILED.value(), "用户名不存在"));
            }

            if (loggedInUser.getUserStatus() == UserEntity.UserStatus.INACTIVE) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error(ResultBean.FORBIDDEN.value(), ResultBean.FORBIDDEN.description()));
            }

            if (!passwordEncoder.matches(user.getPassword(), loggedInUser.getPassword())) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseResult.error(ResultBean.LOGIN_FAILED.value(), "密码错误"));
            }

            // 登录成功，生成 JWT
            String token = JwtUtils.generateToken(loggedInUser.getId());

            // 创建包含用户信息的响应体，但不包含密码
            Map<String, Object> response = new HashMap<>();
            response.put("id", loggedInUser.getId());
            response.put("name", loggedInUser.getName());
            response.put("nickname", loggedInUser.getNickname());
            response.put("phone", loggedInUser.getPhone());
            response.put("email", loggedInUser.getEmail());
            response.put("image",loggedInUser.getImage());
            response.put("Status", loggedInUser.getUserStatus());
            response.put("createTime", loggedInUser.getCreateTime());
            response.put("updateTime", loggedInUser.getUpdateTime());
            response.put("token", token); // 添加 Token 到响应中

            return ResponseEntity.ok().body(ResponseResult.success(response)); // 登录成功，返回用户信息和 Token
        } catch (Exception e) {
            logger.error("登录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error(ResultBean.INTERNAL_SERVER_ERROR.value(), ResultBean.INTERNAL_SERVER_ERROR.description()));
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<ResponseResult<UserEntity>> register(@Valid @RequestBody UserEntity user) {
        try {
            // 验证用户名是否已存在
            UserEntity existingUser = userService.findUserByUsername(user.getName());
            if (existingUser != null) {
                return ResponseEntity.status(HttpStatus.CONFLICT)
                        .body(ResponseResult.error(ResultBean.EXIT_ERROR.value(), ResultBean.EXIT_ERROR.description()));
            }

            // 哈希加密密码
            String hashedPassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(hashedPassword);

            // 设置用户状态为 ACTIVE
            user.setUserStatus(UserEntity.UserStatus.ACTIVE);

            // 设置创建时间
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());


            // 调用 service 方法注册用户
            userService.register(user);

            return ResponseEntity.ok(ResponseResult.success(user)); // 注册成功，返回用户信息
        } catch (DataIntegrityViolationException e) {
            logger.error("注册失败", e);
            return ResponseEntity.status(HttpStatus.CONFLICT)
                    .body(ResponseResult.error(ResultBean.SAVE_FAILED.value(), "用户名已存在"));
        } catch (Exception e) {
            logger.error("注册失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error(ResultBean.INTERNAL_SERVER_ERROR.value(), ResultBean.INTERNAL_SERVER_ERROR.description()));
        }
    }

    /**
     * 更新用户状态 (需要 JWT 鉴权)
     */
    @PutMapping("/updateStatus")
    public ResponseEntity<ResponseResult<UserEntity>> updateUserStatus(@RequestHeader("Authorization") String authorizationHeader, @RequestBody UserEntity userEntity) {
        Long id = userEntity.getId();
        UserEntity.UserStatus userStatus = userEntity.getUserStatus();

        if (id == null || userStatus == null) {
            return ResponseEntity.badRequest().body(ResponseResult.error(ResultBean.NOT_FOUND.value(), ResultBean.NOT_FOUND.description()));
        }

        // 从 Authorization Header 中提取 Token
        String token = extractTokenFromHeader(authorizationHeader);
        if (token == null || !JwtUtils.validateToken(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseResult.error(ResultBean.UNAUTHORIZED.value(), "无效的token"));
        }

        try {
            userService.lockUserById(id, userStatus);
            UserEntity updatedUser = userService.findUserById(id);
            return ResponseEntity.ok(ResponseResult.success(updatedUser));

        } catch (Exception e) {
            logger.error("更新用户状态失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error(ResultBean.INTERNAL_SERVER_ERROR.value(), ResultBean.INTERNAL_SERVER_ERROR.description()));
        }
    }

    // 辅助方法：从 Authorization Header 中提取 Token
    private String extractTokenFromHeader(String authorizationHeader) {
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            return authorizationHeader.substring(7);
        }
        return null;
    }

    //用户修改自己的信息
    @PutMapping("/update")
    public ResponseEntity<ResponseResult> updateUser(@RequestBody UserEntity userEntity, @RequestHeader("Authorization") String authorizationHeader) {
        // 从 Authorization Header 中提取 Token
        String token = extractTokenFromHeader(authorizationHeader);
        if (token == null || !JwtUtils.validateToken(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseResult.error(ResultBean.UNAUTHORIZED.value(), "无效的token"));
        }

        // 从 Token 中获取用户 ID
        Long userId = JwtUtils.getUserIdFromToken(token);

        if (userId == null || !userId.equals(userEntity.getId())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error(ResultBean.FORBIDDEN.value(), "您没有权限修改其他用户的信息"));
        }

        try {
            // 验证用户是否存在
            UserEntity existingUser = userService.findUserById(userId);
            if (existingUser == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ResponseResult.error(ResultBean.NOT_FOUND.value(), "用户不存在"));
            }

            // 设置要更新的用户ID
            userEntity.setId(userId);

            // 执行更新操作
            boolean isUpdated = userService.updateUserById(userEntity);

            if (isUpdated) {
                // 更新成功，返回成功消息
                return ResponseEntity.ok(ResponseResult.success("用户信息更新成功"));
            } else {
                // 更新失败，返回错误消息
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error(ResultBean.MODIFY_FAILED.value(), "用户信息更新失败"));
            }
        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error(ResultBean.INTERNAL_SERVER_ERROR.value(), ResultBean.INTERNAL_SERVER_ERROR.description()));
        }
    }

    //用户修改自己的密码
    @PutMapping("/password/{id}")
    public ResponseEntity<ResponseResult> updatePassword(@PathVariable Long id,
                                                         @RequestParam String oldPassword,
                                                         @RequestParam String newPassword,
                                                         @RequestHeader("Authorization") String authorizationHeader) {

        // 从 Authorization Header 中提取 Token
        String token = extractTokenFromHeader(authorizationHeader);
        if (token == null || !JwtUtils.validateToken(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseResult.error(ResultBean.UNAUTHORIZED.value(), "无效的token"));
        }

        // 从 Token 中获取用户 ID
        Long userId = JwtUtils.getUserIdFromToken(token);

        // 权限验证：确保用户只能修改自己的密码
        if (!userId.equals(id)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error(ResultBean.FORBIDDEN.value(), "您没有权限修改其他用户的密码"));
        }

        try {
            // 验证用户是否存在
            UserEntity existingUser = userService.findUserById(id);
            if (existingUser == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ResponseResult.error(ResultBean.NOT_FOUND.value(), "用户不存在"));
            }

            // 验证旧密码是否正确
            if (!passwordEncoder.matches(oldPassword, existingUser.getPassword())) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ResponseResult.error(ResultBean.PASSWORD_ERROR.value(), "旧密码不正确"));
            }

            // 哈希加密新密码
            String hashedPassword = passwordEncoder.encode(newPassword);

            // 执行更新密码操作
            boolean isUpdated = userService.updatePassword(id, hashedPassword);

            if (isUpdated) {
                return ResponseEntity.ok(ResponseResult.success("密码更新成功"));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error(ResultBean.MODIFY_FAILED.value(), "密码更新失败"));
            }
        } catch (Exception e) {
            logger.error("更新密码失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error(ResultBean.INTERNAL_SERVER_ERROR.value(), ResultBean.INTERNAL_SERVER_ERROR.description()));
        }
    }
}